package org.tvolkov.mycompany

class DivisionService {
	
	static final def NAME_TOKEN = "name";
	static final def PHONE_TOKEN = "phone";
	static final def COMPANY_TOKEN = "parentNode";
	static final def PARENT = "parentCompany";
	
	def getDivisionList(params){
		println("DivisionService: getDivisionList: params: " + params);
		def name = Company.get(params["id"]);
		return Division.findAllByCompany(name).collect{[
			text : it.name,
			id   : ("division" + it.id)
		]};
	}
	
	def addNewDivision(params){
		println("DivisionService: addNewDivision: params: " + params);
		def parentCompany = params["parentCompany"];
		if (parentCompany){
//			def newDivision = new Division(name: params["name-inputEl"], company: Company.get(parentCompany));
			def newDivision = new Division();
			if (params[NAME_TOKEN]){
				newDivision.name = params[NAME_TOKEN];
				println("DivisionService: addNewDivision: set name " + newDivision.name);
			}
			if (params[PHONE_TOKEN]){
				newDivision.phoneNumber = params[PHONE_TOKEN];
				println("DivisionService: addNewDivision: set name " + newDivision.phoneNumber);
			}
			if (params[PARENT]){
				def company = Company.get(params[PARENT]);
				if (company != null){
					newDivision.company = company;
				}
			} 
			if (newDivision.save() != null){
				println("DivisionService: addNewDivision: save ok");
				return ["success": "true"];
			} else {
				println("DivisionService: addNewDivision: save fail1");
				return ["success": "false"];
			}
		} else {
			return ["success": "false"];
		}
	}
	
	def removeDivision(params){
		Division.get(params["nodeid"]).delete();
		return ["success": "true"];	
	}
	
	def getDivisionDetails(params){
		def division = Division.get(params["nodeid"]);
		return [text: division.name,
				id: ("division" + division.id),
				phone: division.phoneNumber];
	}
	
	def editDivision(params){
		println("DivisionService: editDivision: params: " + params);
		def division = Division.get(params["nodeid"]);
		if (params[NAME_TOKEN]){
			if (division.name != params[NAME_TOKEN]){
				division.name = params[NAME_TOKEN];
				println("DivisionService: editDivision: set name " + params[NAME_TOKEN]);
			} else {
				println("DivisionService: editDivision: set name fail");
			}
		}
		if (params[PHONE_TOKEN]){
			if (division.phoneNumber != params[PHONE_TOKEN]){
				division.phoneNumber = params[PHONE_TOKEN];
				println("DivisionService: editDivision: set phoneNumber " + params[PHONE_TOKEN]);
			} else {
				println("DivisionService: editDivision: set phoneNumber fail");
			}
			
		}
		
		if (division.save()){
			return ["success": "true"];
		} else {
			return ["success": "false"];
		}
	}
}
